package org.aiforum.backend.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;

import org.aiforum.backend.common.CacheContext;
import org.aiforum.backend.common.LoginRequest;
import org.aiforum.backend.common.QueryPreperty;
import org.aiforum.backend.common.Response;
import org.aiforum.backend.mapper.AdminAuthMapper;
import org.aiforum.backend.mapper.AdminMapper;
import org.aiforum.domain.Admin;
import org.aiforum.domain.AdminAuth;
import org.aiforum.domain.Auth;
import org.aiforum.util.MD5Util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.util.StringUtil;
/**
 * 管理员业务实现
 * @author Administrator
 *
 */
@Service("adminService")
@Transactional(TxType.REQUIRED)
public class AdminServiceImpl  implements AdminService{
	
	private Logger logger=LogManager.getLogger(getClass());
	@Autowired
	private AdminMapper adminMapper;//注入管理员映射器
    
	@Autowired
	private AdminAuthMapper adminAuthMapper;//注入管理员权限映射器
	
	@Autowired
	private VerificationCodeService verificationCodeService;//注入验证码业务接口
	
	@Autowired
	private AuthService  authService;//注入权限接口
	
	@Override
	public Response insert(Admin admin, int[] authIds) {
		//初始化管理员对象
		admin.setState(1);
		admin.setPassword(MD5Util.encryptMD5(admin.getPassword()));
		admin.setCreateDate(new Date());
		
		adminMapper.insert(admin);
		insertAdminAuth(admin,authIds);
		
		Response repsonse=Response.getInstaner();
		repsonse.setState(true);
		repsonse.setMessage("Add success");
		return repsonse;
	}

	private void insertAdminAuth(Admin admin, int[] authIds) {
		// 添加管理员权限
		if(null != authIds && authIds.length > 0){
			// 批量添加管理员权限
			List<AdminAuth> adminAuths = new ArrayList<AdminAuth>();
			for(int authId : authIds){
				adminAuths.add(new AdminAuth(admin.getAdminId(),authId));
			}
			adminAuthMapper.insert(adminAuths);
		}
	}
	@Override
	public Response update(Admin admin, int[] authIds) {
		//初始化管理员对象
		admin.setState(1);
		adminMapper.update(admin);
		//查询管理员原权限
		List<AdminAuth> adminAuths=adminAuthMapper.findByAdminId(admin.getAdminId());
		if(null!=adminAuths&&adminAuths.size()>0){
			// 批量删除管理员员权限
			 adminAuthMapper.delete(adminAuths);
		}
		// 批量插入管理员新权限
		insertAdminAuth(admin,authIds);
		
		Response repsonse=Response.getInstaner();
		repsonse.setState(true);
		repsonse.setMessage("Update success");
		return repsonse;
	}

	@Override
	public Admin find(int adminId) {
		Admin admin=adminMapper.findById(adminId);
		return admin;
	}

	@Override
	public Response delete(int adminId) {
		adminMapper.delete(adminId);
		adminAuthMapper.deleteByAdminId(adminId);
		Response response=Response.getInstaner();
		response.setState(true);
		response.setMessage("Delete success");
		return response;
	}

	@Override
	public List<Admin> queryByPreperty(QueryPreperty queryPreperty) {
		//如果查询的属性值不为NULL或""
				if(StringUtil.isNotEmpty(queryPreperty.getQueryValue().toString())){
					//构建模糊查询条件
					String value="%"+queryPreperty.getQueryValue()+"%";
					queryPreperty.setQueryValue(value);
				}else{
					//否则设置为空
					queryPreperty.setQueryValue(null);
				}
				return adminMapper.queryByPreperty(queryPreperty);
	}

	@Override
	public Response checkExists(QueryPreperty queryPreperty) {
		//根据属性查询是否有记录
				int count=adminMapper.checkExists(queryPreperty);
				Response response=Response.getInstaner();
				if(count>0){
					response.setState(true);
					response.setMessage(queryPreperty.getQueryName()+"already exists");
				}
				return response;
	}

	@Override
	public List<Integer> auths(Integer adminId) {
		// 根据管理员ID查询管理员所拥有的权限集合
		List<AdminAuth> adminAuths=adminAuthMapper.findByAdminId(adminId);
		List<Integer>  auths=new ArrayList<Integer>();
		// 将权限集合转换为权限ID集合
		if(null!=adminAuths && adminAuths.size()>0){
			 for(AdminAuth adminAuth:adminAuths){
				 auths.add(adminAuth.getAuthId());
			 }
		}
		return auths;
	}

	@Override
	public Response login(LoginRequest loginRequest) {
		//检查验证码
		Response response=verificationCodeService.checkVerificaionCode(loginRequest.getCode());
		//如果验证码错误
		if(!response.isState()){
			return response;
		}
		//删除缓存的验证码
		verificationCodeService.removeVerificationCode(loginRequest.getCode());
		
		//查询账号
		QueryPreperty queryPreperty=new QueryPreperty();
		queryPreperty.setQueryName("account");
		queryPreperty.setQueryValue(loginRequest.getAccount());
		List<Admin> admins=adminMapper.queryByPreperty(queryPreperty);
		
		//如果账号不存在
		if(null==admins||admins.size()<0){
			response.setMessage("account not exists");
			return response;
		}
		//账号存在
		Admin admin=admins.get(0);
		
		//如果账号不可用
		if(admin.getState()!=1){
			response.setMessage("account already lock");
			response.setState(false);
			return response;
		}
		
		//匹配密码
		if(admin.getPassword().equals(MD5Util.encryptMD5(loginRequest.getPassword()))){
			// 登录成功
			response.setState(true);
			// 设置登录成功跳转到首页控制器
			response.setMessage("index");
			// 查询管理员权限ID集合
			List<Integer> authIds = auths(admin.getAdminId());
			// 查询管理员权限对象
			List<Auth> auths = authService.queryByIds(authIds);
			// 构建token
			String token = MD5Util.encryptMD5(admin.toString());
			// 缓存15分钟
			long timeout = System.currentTimeMillis() + (1000 * 60 * 15);
			// 设置管理员权限
			admin.setAuths(auths);
			// 缓存管理员
			CacheContext.setCache(token, admin, timeout);
			// 设置token
			response.setData(token);
					}else{
						// 密码错误
						response.setMessage("password error");
						response.setState(false);
					}
					return response;
				}

	@Override
	public void logout(String token) {
		 CacheContext.delCache(token);
	}

	@Override
	public void initSuperAdmin() {
		logger.info("start init super admin.");
		//构建原查询超级管理员
		QueryPreperty queryPreperty=new QueryPreperty();
		queryPreperty.setQueryName("account");
		queryPreperty.setQueryValue("superadmin");
		List<Admin> admins=adminMapper.queryByPreperty(queryPreperty);
		if(null!=admins&&admins.size()>0){
			//获取原超级管理原
			Admin oldSuperAdmin=admins.get(0);
			//删除原超级管理员
			adminMapper.delete(oldSuperAdmin.getAdminId());
			logger.info("delete oldsuperadmin");
			
			//获取原管理员所有权限
			List<AdminAuth> adminAuths=adminAuthMapper.findByAdminId(oldSuperAdmin.getAdminId());
			if(null!=adminAuths&&adminAuths.size()>0){
				//删除所有权限
				adminAuthMapper.delete(adminAuths);
				logger.info("delete oldsuper admin auth");
				
			}
		}
		  //构建超级管理员对象
		Admin superAdmin=new Admin();
		superAdmin.setAccount("superadmin");
		superAdmin.setPassword(MD5Util.encryptMD5("superadmin"));
		superAdmin.setCreateDate(new Date());
		superAdmin.setState(1);
		superAdmin.setEmail("superadmin@163.com");
		superAdmin.setHead("");
		
		// 插入超级管理员
		adminMapper.insert(superAdmin);
		logger.info("insert new super admin.");
		
		// 获取系统所有权限
		queryPreperty.setQueryName("state");
		queryPreperty.setQueryValue(1);
		List<Auth> auths = authService.querys(queryPreperty);
		
		// 构建管理员权限集合
		List<AdminAuth> adminAuths = new ArrayList<AdminAuth>();
		for(Auth auth : auths){
			adminAuths.add(new AdminAuth(superAdmin.getAdminId(), auth.getAuthId()));
		}
		
		// 批量插入管理员权限
		adminAuthMapper.insert(adminAuths);
		logger.info("end init superme admin.");

		
	}
}
